const log4js=require('log4js');

const log_config=require('../config/log4js.js');

//加载配置文件
log4js.configure(log_config);

let logUtil={};

let errorLogger=log4js.getLogger('errorLogger');
let resLogger=log4js.getLogger('resLogger');

//封装错误日志
logUtil.logError=function (ctx,error,resTime){
  if(ctx&&error){
    errorLogger.error(formatError(ctx,error,resTime))
  }
}

//封装响应类型的错误日志
logUtil.logResponse=function (ctx,resTime){
  if(ctx){
    resLogger.info(formatRes(ctx,resTime))
  }
}

//格式化响应日志
function formatRes (ctx,resTime) {
  let logText = new String();

  //响应日志的开始
  logText += "\n" + "********************response log start*****************" + "\n";

  //添加请求日志
  logText += formatReqLog(ctx.request,resTime);

  //添加响应状态码
  logText += + "response status: " + ctx.status + "\n";

  //添加响应内容
  logText += "response body: " + "\n" + JSON.stringify(ctx.body) + "\n";

  //添加结束日志标志
  logText += "******************response log end****************" + "\n";

  return logText;
}

//格式化错误日志
function formatError (ctx,error,resTime) {
  let logText = new String();

  //错误日志开始
  logText += "\n" + "*****************error log start****************" + "\n";

  //添加请求日志
  logText += formatReqLog(ctx.request,resTime);

  //错误名称
  logText += + "error name: " + error.name + "\n";

  //错误信息
  logText += "error message: " + error.message + "\n";

  //错误信息详情
  logText += "error stack: " + error.stack + "\n";

  //错误信息结束
  logText += "*************** error log end ***************" + "\n";

  return logText;
}

//格式化请求日志
function formatReqLog (req,resTime){
  let logText = new String(),
      method = req.method;

  //访问方法
  logText += "request method : " + method + "\n";

  //请求原始地址
  logText += "request originalUrl:" + req.originalUrl + "\n";

  //客户端id
  logText += "request client id:" + req.id + "\n";

  let startTime;

  //请求参数
  if (method === "GET") {
    logText += "request query:  " + JSON.stringify(req.query) + "\n";
        // startTime = req.query.requestStartTime;
  } else {
        logText += "request body: " + "\n" + JSON.stringify(req.body) + "\n";
        // startTime = req.body.requestStartTime;
  }

  //服务器响应时间
  logText += "response time: " + resTime + "\n";

  return logText;
}

module.exports = logUtil;
